package com.example.music.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.music.model.User;
import com.example.music.service.UserService;
import com.example.music.utils.Constant;
import com.example.music.utils.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * ClassName: UserController
 * Package: com.example.music.controller
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-05-29
 * Time: 18:08
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户模块接口")
public class UserController {

    @Autowired
    private UserService userService;

    //在使用BCryptPasswordEncoder之前 要在配置类中@Bean注入BCryptPasswordEncoder
    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    //登录请求
    /**
     * 请求
     * post，
     * /user/login
     * data:{username,password}
     */

    /**
     * 响应
     * "status":0,
     * "message":"登录成功",
     * "data":{
     *     "id":****,
     *     "username":****,
     *     "password":****
     * }
     */

    @ApiOperation("登录接口")
    @PostMapping("/login")
    public Result<User> login(@ApiParam("用户名") String username,
                              @ApiParam("密码") String password, HttpServletRequest request){
        //先去查用户名 存在用户 在对比密码
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userService.getOne(queryWrapper);
        if (user == null){
            return new Result<>(-1,"用户名不存在",null);
        }

        //bCryptPasswordEncoder.encode(); 这个是加密 encode编码
        //matches 比对 第一个参数是普通密码 第二个参数是加密的密码
        boolean matches = bCryptPasswordEncoder.matches(password,user.getPassword());
        //不为空 对比密码 字符串对比 equals
        if (matches){
            //登录成功之后 存入Session
            HttpSession session = request.getSession(true);

            //key值定义为静态不变常量
            session.setAttribute(Constant.USERINFO_SESSION_KET,user);

           return new Result<>(0,"登录成功",user);
        }

        //密码不正确
        return new Result<>(-1,"密码错误",null);

    }

}
